package com.smfx.yxt.controller.teacher;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smfx.yxt.common.AppUser;
import com.smfx.yxt.common.Const;
import com.smfx.yxt.common.MenuConst;
import com.smfx.yxt.common.RspResult;
import com.smfx.yxt.common.enums.RelationType;
import com.smfx.yxt.common.enums.Status;
import com.smfx.yxt.common.enums.WorkApprovalStatus;
import com.smfx.yxt.common.enums.WorkApprovalType;
import com.smfx.yxt.controller.BaseController;
import com.smfx.yxt.model.Grid;
import com.smfx.yxt.model.TeacherOrganizeGroup;
import com.smfx.yxt.model.WorkApproval;
import com.smfx.yxt.model.WorkApprovalConf;
import com.smfx.yxt.page.OrderBy;
import com.smfx.yxt.page.Page;
import com.smfx.yxt.reqVo.WorkApprovalReqVO;
import com.smfx.yxt.service.IOrganizeDepartService;
import com.smfx.yxt.service.IWorkApprovalConfService;
import com.smfx.yxt.service.IWorkApprovalService;
import com.smfx.yxt.utils.DateUtil;
import com.smfx.yxt.utils.StringUtil;
import com.smfx.yxt.view.WorkApprovalView;
import com.smfx.yxt.vo.WorkApprovalQueryVO;

@RequestMapping(Const.TEACHER_ROLE + MenuConst.WORK_APPROVAL)
@Controller
public class WorkApprovalController extends BaseController{

	private Logger logger = LoggerFactory.getLogger(WorkApprovalController.class);
	
	@Autowired
	private IWorkApprovalService workApprovalService;
	@Autowired
	private IOrganizeDepartService organizeDepartService;
	@Autowired
	private IWorkApprovalConfService workApprovalConfService;
	
	@RequestMapping(value={"","/"})
	public String workApproval() {
		AppUser appUser = getAppUser();
		if(workApprovalService.isApprover(appUser.getTeacher().getId())) {
			return "workApproval/approverList";
		}
		return "workApproval/list";
	}
	
	@RequestMapping("{type}/add")
	public String addApproval(Model model, @PathVariable String type) {
		if(WorkApprovalType.getDesc(type) != null) {
			model.addAttribute("approvalType", type);
			return "workApproval/" + type;
		}
		return null;
	}
	
	@RequestMapping("apply")
	public String workApprovalApply(Model model) {
		model.addAttribute("relationType", RelationType.WORK_APPROVAL.getCode());
		return "workApproval/apply";
	}
	
	//工作审批提交
	@RequestMapping("apply/submit")
	@ResponseBody Object applySubmit(WorkApprovalReqVO reqVO) {
		try {
			AppUser appUser = getAppUser();
			reqVO.setSchoolId(appUser.getTeacher().getSchoolId());
			reqVO.setSchoolName(appUser.getTeacher().getSchoolName());
			reqVO.setDepart(appUser.getTeacher().getDepartText());
			reqVO.setApplyer(appUser.getTeacher().getName());
			reqVO.setApplyerId(appUser.getTeacher().getId());
			reqVO.setStartTime(DateUtil.strToDate(reqVO.getStartDate(), DateUtil.DEFAULT_DATE_FORMAT1));
			reqVO.setEndTime(DateUtil.strToDate(reqVO.getEndDate(), DateUtil.DEFAULT_DATE_FORMAT1));
			
			workApprovalService.addWorkApproval(reqVO);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("----applySubmit error={}", e);
		}
		return new RspResult(Status.FAIL);
	} 
	/**
	 * 分页查询工作审批
	 * @param vo
	 * @return
	 */
	@RequestMapping("page/query")
	@ResponseBody Object pageQuery(WorkApprovalQueryVO vo) {
		try {
			Page<WorkApprovalView> page = new Page<WorkApprovalView>();
			Grid grid = new Grid();
			List<OrderBy> sorts = new ArrayList<>();
			sorts.add(new OrderBy("APPLY_TIME", "desc"));
			sorts.add(new OrderBy("APPROVAL_TIME", "desc"));
			page.setSorts(sorts);
			page.setParams(vo);
			page.setPageNo(vo.getPage());
			page.setPageSize(vo.getRows());
			List<WorkApprovalView> list = workApprovalService.selectViewListByPage(page);
			grid.setRows(list);
			grid.setTotal(page.getTotalRecord());
			return new RspResult(Status.SUCCESS, grid);
		} catch (Exception e) {
			logger.error("--pageQuery error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	/**
	 * 工作审批详情页
	 * @param applyId
	 * @return
	 */
	@RequestMapping("detail/{applyId}")
	public String detail(Model model, @PathVariable Integer applyId) {
		WorkApprovalView view = workApprovalService.selectViewDetail(applyId);
		model.addAttribute("detail", view);
		return "workApproval/detail";
	}
	/**
	 * 审批通过
	 * @param reqVO
	 * @return
	 */
	@RequestMapping("success")
	@ResponseBody Object approvalSuccess(WorkApprovalReqVO reqVO) {
		try {
			AppUser appUser = getAppUser();
			WorkApproval workApproval = workApprovalService.selectForApproval(
					reqVO.getApplyId(), appUser.getTeacher().getId());
			if(workApproval != null) {
				if(!workApproval.getApprovalStatus().equals(WorkApprovalStatus.AUDIT_PENING.getCode())) {
					return new RspResult(Status.EXPIRED_DATA);
				}
				workApproval.setCcList(reqVO.getCcList());
				workApproval.setApprovalStatus(WorkApprovalStatus.AUDIT_SUCCESS.getCode());
				workApproval.setApprovalTime(new Date());
				workApprovalService.updateApproval(workApproval);
				return new RspResult(Status.SUCCESS);
			}
			return new RspResult(Status.APPROVAL_OUT);
		} catch (Exception e) {
			logger.error("---audited error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	/**
	 * 审批驳回
	 * @param reqVO
	 * @return
	 */
	@RequestMapping("reject")
	@ResponseBody Object approvalReject(WorkApprovalReqVO reqVO) {
		try {
			AppUser appUser = getAppUser();
			WorkApproval workApproval = workApprovalService.selectForApproval(
					reqVO.getApplyId(), appUser.getTeacher().getId());
			if(workApproval != null) {
				if(!workApproval.getApprovalStatus().equals(WorkApprovalStatus.AUDIT_PENING.getCode())) {
					return new RspResult(Status.EXPIRED_DATA);
				}
				workApproval.setApprovalStatus(WorkApprovalStatus.AUDIT_REJECT.getCode());
				workApproval.setRejectReason(reqVO.getRejectReason());
				workApproval.setApprovalTime(new Date());
				workApprovalService.updateApproval(workApproval);
				return new RspResult(Status.SUCCESS);
			}
			return new RspResult(Status.APPROVAL_OUT);
		} catch (Exception e) {
			logger.error("---audited error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	/**
	 * 获取审批人
	 * @param approvalType
	 * @return
	 */
	@RequestMapping("approver")
	@ResponseBody Object getApprover(String approvalType) {
		try {
			AppUser appUser = getAppUser();
			WorkApprovalConf conf = new WorkApprovalConf();
			conf.setItemCode(approvalType);
			conf.setSchoolId(appUser.getTeacher().getSchoolId());
			WorkApprovalConf record = workApprovalConfService.selectByParam(conf);
			if(record != null && StringUtils.isNotBlank(record.getApprovalerId()) && !"0".equals(record.getApprovalerId())) {
				return new RspResult(Status.SUCCESS, record);
			}
			//组织级别：行政组，级组长，科组长
			String groupIds = "10,20,30";
			List<TeacherOrganizeGroup> list = organizeDepartService.fillTeacherOrganizeGroupByGroupIds(groupIds, appUser.getTeacher().getSchoolId());
			return new RspResult(Status.SUCCESS, list);
		} catch (Exception e) {
			logger.error("---getApprover error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("ccer")
	@ResponseBody Object getCcer(String approvalType) {
		try {
			AppUser appUser = getAppUser();
			WorkApprovalConf conf = new WorkApprovalConf();
			conf.setItemCode(approvalType);
			conf.setSchoolId(appUser.getTeacher().getSchoolId());
			WorkApprovalConf record = workApprovalConfService.selectByParam(conf);
			if(record != null && StringUtils.isNotBlank(record.getCcerId()) 
					&& !record.getCcerId().equals("0")) {
				return new RspResult(Status.SUCCESS, record);
			}
			List<TeacherOrganizeGroup> list = organizeDepartService.fillTeacherOrganizeGroup(appUser.getTeacher().getSchoolId());
			return new RspResult(Status.SUCCESS, list);
		} catch (Exception e) {
			logger.error("---getCcer error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	
	@RequestMapping("revoked")
	@ResponseBody Object revoked(Integer applyId) {
		try {
			AppUser appUser = getAppUser();
			WorkApproval workApproval = workApprovalService.selectByPrimaryKey(applyId);
			if(workApproval != null && workApproval.getApplyerId().intValue() == appUser.getTeacher().getId().intValue()) {
				if(!workApproval.getApprovalStatus().equals(WorkApprovalStatus.AUDIT_PENING.getCode())) {
					return new RspResult(Status.EXPIRED_DATA);
				}
				if((new Date().getTime() - workApproval.getApplyTime().getTime())/1000/60/60 > 2) {
					return new RspResult(Status.TIMEOUT);
				}
				workApproval.setApprovalStatus(WorkApprovalStatus.REVOKED.getCode());
				workApproval.setApprovalTime(new Date());
				workApprovalService.updateApproval(workApproval);
				return new RspResult(Status.SUCCESS);
			}
			return new RspResult(Status.EXPIRED_DATA);
		} catch (Exception e) {
			logger.error("---getApprover error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
}
